<template>
  <div class="userBox">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/mamger' }"
        >用户管理</el-breadcrumb-item
      >
      <el-breadcrumb-item :to="{ path: '/users' }">用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- @blur="getSearchUsers" -->
    <el-card class="box-card">
      <el-row type="flex">
        <el-col :span="12">
          <div class="grid-content bg-purple title" style="text-align: left">
            <el-input
              clearable
              placeholder="请输入内容"
              v-model.trim="params.query"
              class="input-with-select"
              @clear="getSearchUsers"
              @keydown.native.enter="getSearchUsers"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getSearchUsers"
              ></el-button>
            </el-input>
          </div>
        </el-col>

        <el-col :span="12">
          <el-row type="flex">
            <el-col :span="2"></el-col>
            <el-col :span="20">
              <el-button type="primary" @click="dialogFormVisible = true"
                >添加用户</el-button
              >
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-table :data="tableData" border style="width: 100%  margin-top:10px">
        <el-table-column type="index" width="50"> </el-table-column>

        <el-table-column prop="username" label="用户" width="100">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="180">
        </el-table-column>
        <!-- prop="mg_state" -->
        <el-table-column label="状态" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeUserState(scope.row)"
            >
            </el-switch>

            <!-- {{ scope.row }} -->
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >

            <el-button
              size="mini"
              type="warning"
              @click="allocatedLimits(scope.$index, scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--  分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="params.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalpage"
    >
    </el-pagination>

    <!--  添加用户弹框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item
          label="用户名"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码"
          prop="password"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户邮箱"
          prop="email"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </div>
    </el-dialog>

    <!--  编辑用户弹框 -->

    <el-dialog title="编辑用户" :visible.sync="editeDialogFormVisible">
      <el-form :model="editeForm" ref="form" :rules="rules">
        <el-form-item
          label="用户名"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editeForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码"
          prop="password"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="editeForm.password"
            disabled
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="用户邮箱"
          prop="email"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editeForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editeForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editeDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUsers">编辑确定</el-button>
      </div>
    </el-dialog>

    <!--  分配权限弹框 -->

    <!-- <el-button type="text" @click="dialogFormVisibleLimits = true">打开嵌套表单的 Dialog</el-button> -->

    <el-dialog title="分配角色" :visible.sync="dialogFormVisibleLimits">
      <el-form :model="limitsForm">
        <el-form-item label="当前的用户:" :label-width="formLabelWidth">
          <el-tag type="success">{{ limitsForm.username }}</el-tag>
          <!-- <el-input v-model="formLimits.name" autocomplete="off"></el-input> -->
        </el-form-item>
        <el-form-item label="当前的角色:" :label-width="formLabelWidth">
          <el-tag type="success">{{ limitsForm.role_name }}</el-tag>
          <!-- <el-input v-model="formLimits.name" autocomplete="off"></el-input> -->
        </el-form-item>
        <el-form-item label="分配新角色:" :label-width="formLabelWidth">
          <el-select v-model="roleValue" placeholder="请选择">
            <el-option
              v-for="item in rolesUsers"
              :key="item.value"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleLimits = false">取 消</el-button>
        <el-button type="primary" @click="setUsersRoles"
          >确定设置角色</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsers,
  getChangeUserState,
  getAddUsers,
  getDeleteUsers,
  getQueryUsersById,
  getEditUsers,
  getUsersRole,
  getRoles,
} from "../../api/index";

export default {
  data() {
    var validateMobile = (rule, value, callback) => {
      let regMobile = /^[1]([3-9])[0-9]{9}$/;

      if (!regMobile.test(value)) {
        callback(new Error("手机号码输入不规范"));
      } else {
        callback();
      }
    };

    return {
      role_id: 0, // 定义角色id
      tableData: [
        {
          id: 25,
          username: "tige117",
          mobile: "18616358651",
          type: 1,
          email: "tige112@163.com",
          create_time: "2017-11-09T20:36:26.000Z",
          mg_state: true, // 当前用户的状态
          role_name: "炒鸡管理员",
        },
      ],
      totalpage: 0, //总页数
      params: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      //分页

      // 定义弹框数据

      dialogFormVisible: false,
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      formLabelWidth: "200px",
      //验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],

        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
        ],
        email: [{ required: true, message: "请输入用户邮箱", trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      },

      //编辑用户数据定义
      editeDialogFormVisible: false,
      editeForm: {
        username: "",
        password: "123456",
        email: "",
        mobile: "",
      },
      //定义分配权限数据
      dialogFormVisibleLimits: false,
      limitsForm: {
        username: "",
        role_name: "",
      },
      rolesUsers: [], // 用户角色初始数据
      roleValue: "", //定义角色的id值
    };
  },

  created() {
    this.getUsersList();
  },
  methods: {
    //初始化获取用户列表
    async getUsersList() {
      let {
        data: { users, pagenum, total },
      } = await getUsers(this.params);

      this.tableData = users;
      this.params.pagenum = pagenum;
      this.totalpage = total;
    },
    //分页功能
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.params.pagesize = val;
      this.getUsersList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.pagenum = val;
      this.getUsersList();
    },

    //搜索功能
    getSearchUsers() {
      this.getUsersList();
    },

    //改变用户状态
    async changeUserState(data) {
      console.log(data);
      console.log({ id: data.id, type: data.mg_state });

      let res = await getChangeUserState({ id: data.id, type: data.mg_state });
      console.log(res);

      // meta:
      // msg: "设置状态成功"
      // status: 200

      let {
        meta: { msg, status },
      } = res;
      if (status == 200) {
        this.$message({ type: "success", message: msg });
        //更改状态后刷新页面
        this.getUsersList();
      }
    },

    //添加用户逻辑
    async addUsers() {
      //   1 表单的验证
      //   2 验证通过后 发送请求
      //   3 发送请求成功后关闭弹框  重新刷新页面

      //  1 表单的验证
      let success = await this.$refs["form"].validate().catch(() => {});
      console.log(success);

      if (!success) return false;
      // 2 验证通过后 发送请求
      let {
        meta: { status },
      } = await getAddUsers(this.form);

      if (status == 201) {
        this.$message.success("添加用户成功");
        //关闭弹框
        this.dialogFormVisible = false;
        // 重新刷新页面
        this.getUsersList();
      }
    },

    // 删除用户
    async handleDelete(index, item) {
      console.log(index);
      console.log(item);
      //1  判断是否真的要删除  如果 点击取消删除 那么什么都不做 给出取消删除的提示
      // 2 如果是真的要删除  发送ajax 请 求  判断回来的数据 请求成功后 执行删除的提示
      // 3 重新加载页面
      let res = await this.$confirm("此操作将永久删除该文件, 是否继续?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {}); // 这里的取消必须加上一个catch 的回调函数
      if (res != "confirm") return this.$message.info("取消删除");
      let {
        meta: { status, msg },
      } = await getDeleteUsers({ id: item.id });

      if (status == 200) {
        this.$message.success("删除成功");
        this.getUsersList(); // 3 重新加载页面
      } else {
        this.$message.error("删除失败");
      }
    },

    // 编辑用户功能
    // 1 点击 弹出编辑对话框  2 把点击的当前这个一项数据 展示在都对应的input 里面 (通过 id )
    //  从 后台去查询对应的这一条数据
    // 3  修改对应的数据 修改后进行 数据的编辑请求  成功后 关闭对话框,重新刷新页面
    async handleEdit(index, item) {
      // 1 根据id 发送请求
      let res = await getQueryUsersById({ id: item.id });
      let {
        data,
        meta: { status },
      } = res;
      if (status != 200) return this.$message.info("查询失败了");
      this.editeForm = data;
      this.role_id = data.role_id;

      this.editeDialogFormVisible = true;
    },
    // 2 真正的修改完数据后进行数据编辑

    async editUsers() {
      let {
        meta: { status },
      } = await getEditUsers(this.editeForm);
      if (status != 200) return this.$message.info("编辑失败了");

      this.editeDialogFormVisible = false;
      this.getUsersList();
    },
    // 分配权限
    async allocatedLimits(index, item) {
      console.log(item);
      // 1 获取角色列表
      let { data: rolesList } = await getRoles();
      console.log(rolesList);
      //方式一
      // let arr = [];
      // rolesList.data.map((item) => {
      //   let rolesObj = { id: item.id, roleName: item.roleName };
      //   arr.push(rolesObj);
      // });
      // console.log(arr);

      //  方式二
      let newArr = rolesList.reduce((preVal, currentItem) => {
        return [
          ...preVal,
          { id: currentItem.id, roleName: currentItem.roleName },
        ];
      }, []);

      console.log(newArr);
      this.rolesUsers = newArr;

      //1 打开弹框
      this.dialogFormVisibleLimits = true;

      //2 对应的当前用的值 用户名 和角色 显示出来
      this.limitsForm.username = item.username;
      this.limitsForm.role_name = item.role_name;
      this.limitsForm.id=item.id
      //  this.setUsersRoles(item)
    },

    async setUsersRoles(item) {
      //3 点击下拉框 发送请求   拿到数据 渲染 下拉的值
      // 获取用户级的分配角色 id  this.roleValue
      let res = await getUsersRole({ id:  this.limitsForm.id, rid: this.roleValue });
      console.log(res);
      let {
        meta: { msg, status },
      } = res;
      if (status != 200) return this.$message.error("修改失败");
      //4 真正的点击确认按钮  分配好角色后 关闭弹框  刷新页面
      this.$message.success("修改成功");
      this.getUsersList();
      this.dialogFormVisibleLimits = false;
    },
  },
};
</script>

<style scoped>
.box-card {
  width: 1200px;
}
.userBox {
  padding-left: 20px;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin: 20px auto;
  text-align: center;
}
</style>
